/*
Global Api, handling all the model and collection fetch

facade = Radio.channel('facade');
facade.request('get:collection', 'sale_products');
*/
import Mn from 'backbone.marionette';
import Radio from 'backbone.radio'
import SheetModel from 'statistics/models/SheetModel.js';
import FacadeModelApiMixin from 'base/components/FacadeModelApiMixin.js';
import EntryCollection from 'statistics/models/EntryCollection.js';
import {CriteriaCollection} from 'statistics/models/criterion';
import { ajax_call } from '../../tools';


const FacadeClass = Mn.Object.extend(FacadeModelApiMixin).extend({
    radioEvents: {
        'criterion:add': 'onAddCriterion',
    },
    radioRequests: {
        'get:model': 'getModelRequest',
        'get:collection': 'getCollectionRequest',
        'get:entry': "getEntry",
        'load:collection': 'loadCollection',
        'is:valid': "isDatasValid",
        'load:criteria': 'loadCriteriaCollection',
        'entry:duplicate': 'onEntryDuplicate',
    },
    initialize(options){
        this.models = {};
        this.models['sheet'] = new SheetModel({});
        this.collections = {};
        let collection;

        collection = new EntryCollection();
        this.collections['entries'] = collection;

    },
    setup(options){
        this.setModelUrl('sheet', options['context_url']);
		this.setCollectionUrl('entries', options['entries_url']);
    },
    getEntry(entryId){
        console.log(" - Facade : Retrieving entry " + entryId);
        return this.collections['entries'].get(entryId)
    },
    loadCriteriaCollection(entry){
        console.log(" - Facade : Retrieving the criteria defining the entry " + entry.get('id'));
        const col = this.collections['criteria'] = new CriteriaCollection();
        col.url = entry.criteria_url();
        return this.loadCollection('criteria')
    },
    onAddCriterion(model){
        model.url = this.collections.criteria.url;
        let channel = Radio.channel('facade');
        const request = model.save({wait: true, sort: true});
        request.then(
            (result) => this.collections.criteria.fetch(
                {
                    reset: true,
                    success: (result) => channel.trigger('criterion:added')
                }
            )
        );
    },
    onEntryDuplicate(model, sheetId){
        const sameSheet = parseInt(model.get('sheet_id')) == parseInt(sheetId);
        let request = ajax_call(model.duplicateUrl(), {sheet_id: sheetId}, 'POST');
        if (sameSheet){
            request = request.then(
                (result) => this.collections.entries.fetch()
            );
        }
        return request;
    },
    start(){
        /*
         * Fires initial One Page application Load
         */
        let modelRequest = this.loadModel('sheet');
        let collectionRequest = this.loadCollection('entries');
        return $.when(modelRequest, collectionRequest);
    }
});
const Facade = new FacadeClass();
export default Facade;
